package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author yaya
 * @Create 2024/5/29 15:02
 * Description:
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    // targetType:泛型类T , T 必须继承BaseEnum接口，必须拥有code，name属性，这样就方便了操作
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        // 匿名内部类当场实现接口并返回
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                return Arrays.stream(targetType.getEnumConstants())
                        .filter(type -> source.equals("" + type.getCode()))
                        .findFirst()
                        .orElseThrow(IllegalArgumentException::new);
            }
        };
    }
}
